<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">参数</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="参数"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">冰箱</label>
        <el-select
          v-model="query.cabinetId"
          clearable
          style="width: 185px;"
          placeholder="冰箱"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in refrigeratorOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
      </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="name" label="参数" align="center" />
        <el-table-column prop="category" label="类别" align="center" />
        <el-table-column prop="labName" label="实验室" />
        <el-table-column prop="cabinetName" label="试剂柜" />
        <el-table-column prop="number" label="编号" align="center" />
        <!-- <el-table-column prop="batchNumber" label="批号" align="center" /> -->
        <el-table-column prop="matrix" label="基体" align="center" />
        <el-table-column prop="totalNumber" label="库存" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.unit == 1">{{ scope.row.totalNumber }} 支</span>
            <span v-if="scope.row.unit == 2">{{ scope.row.totalNumber }} mL</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="cabinetName" label="冰箱" align="center"/> -->
        <el-table-column prop="ingredientData" label="成分" align="center">
          <template slot-scope="scope">
           <el-button type="primary" plain @click="showIngredientDialog(scope.row.ingredientData)">查看成分</el-button>
           <el-button
              type="primary"
              class="isForbiddenBtn"
              @click="showDialog(scope.row)"
              >盘平</el-button
            >
          </template>
        </el-table-column>
        <!-- <el-table-column prop="expirationDate" label="有效期" align="center" width="135"/> -->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <AddNumDialog v-if="isShowAddNumDialog" @refresh="crud.pageChangeHandler(0)" @close="isShowAddNumDialog = false"  :isShowAddNumDialog="isShowAddNumDialog" :type="type" :name="name"/>

    <ingredientInfoDialog :info="currentShowIngredient" :ingredientDialog="ingredientDialog" @close="ingredientDialog=false" />
  </div>
</template>

<script>
import crudHazardousChemicals ,{searchIdAndType,getListAPI}from '@/api/hazardousChemicals'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { get } from '@/api/lab'
import { getCabinet } from '@/api/cabinet'
import ingredientInfoDialog from "@/components/ingredientInfoDialog.vue";
import { mapState } from 'vuex'
import { getRefrigeratorListAPI } from "@/api/refrigerator";
import AddNumDialog from "./components/addNumConsumableDialog.vue";

const defaultForm = {
  id: null,
  name: null,
  type: 2,
  amount: null,
  labId: null,
  note: null,
  createdAt: null,
  isDeleted: null,
  countType: null,
  updatedAt: null,
  barCode: null,
  cabinetId: null,
  measureId: 1,
  dangerClasses: null,
  totalNum: null
}
export default {
  name: 'StandardSubstanceStorehouse',
  components: { pagination, crudOperation, rrOperation, udOperation ,ingredientInfoDialog,AddNumDialog},
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '标准物质盘库',
      url: 'api/hazardousChemicalsTotal/hazardousChemicalsTotalList',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudHazardousChemicals },
      query: {
        type: 2
      },
      optShow: {
      add: false,
      edit: false,
      del: false,
      download: true,
      reset: true
    },
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'hazardousChemicals:add'],
        edit: ['admin', 'hazardousChemicals:edit'],
        del: ['admin', 'hazardousChemicals:del']
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        // type: [
        //   { required: true, message: '危化品类型不能为空', trigger: 'blur' }
        // ],
        amount: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
        labId: [
          { required: true, message: '实验室不能为空', trigger: 'change' }
        ],
        countType: [
          { required: true, message: '计数类型不能为空', trigger: 'blur' }
        ],
        cabinetId: [
          { required: true, message: '试剂柜不能为空', trigger: 'change' }
        ],
        // measureId: [
        //   { required: true, message: '计量方式不能为空', trigger: 'blur' }
        // ],
        dangerClasses: [
          { required: true, message: '危险等级不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '名称' },
        // { key: 'type', display_name: '危化品类型' },
        { key: 'labName', display_name: '实验室' },
        { key: 'countType', display_name: '计数类型' },
        // { key: 'measureId', display_name: '计量方式' },
        { key: 'dangerClasses', display_name: '危险等级' }
      ],
      searchLoading: false,
      labs: [],
      cabinets: [],
      searchForm: {
        page: 1,
        size: 1000,
        name: '',
        id: ''
      },
      refrigeratorOptions: [],
      ingredientDialog: false,
      currentShowIngredient:[],
      isShowAddNumDialog:false,
      currentAddNumDialogInfo:[],
      name:'',
      type:''
    }
  },
   created() {
    this.getLabs()
    this.getRefrigerator()
  },
  computed: {
    ...mapState('hjuser', ['systemSearchInfoId'])
  },
  methods: {
    async getRefrigerator(){
      const res  = await getRefrigeratorListAPI()
      this.refrigeratorOptions = res
    },
    getLabs(query = '') {
      this.searchForm.name = query
      this.searchLoading = true
      get()
        .then(response => {
          this.searchLoading = false
          this.labs = response
        })
        .catch(_ => {
          this.searchLoading = false
        })
    },
    onChanged(value) {
      this.searchForm.name = ''
      this.searchLoading = true
      getCabinet(this.searchForm)
        .then(response => {
          this.searchLoading = false
          this.cabinets = response.content
          this.cabinets = this.cabinets.filter(item => {
            return item.labId == value
          })
          if (this.cabinets.length != 0) {
            this.form.cabinetId = this.cabinets[0].id
          } else {
            this.form.cabinetId = null
          }
        })
        .catch(_ => {
          this.searchLoading = false
        })

      console.log(this.cabinets)
    },
    fileDownload(downloadUrl) {
      downloadUrl = 'data:image/jpeg;base64,' + downloadUrl
      console.log(downloadUrl)
      const aLink = document.createElement('a')
      aLink.style.display = 'none'
      aLink.href = downloadUrl
      aLink.download = '条形码.png'
      // 触发点击-然后移除
      document.body.appendChild(aLink)
      aLink.click()
      document.body.removeChild(aLink)
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    async [CRUD.HOOK.afterRefresh]() {
      this.crud.data = this.crud.data.map(
        item =>
          (item = {
            ...item,
            unit: Number(item.unit),
            ingredientData: (item.ingredientData&&JSON.parse(item.ingredientData))|| []
          })
      )
      if (this.systemSearchInfoId) {
        try {
          const res = await searchIdAndType(this.systemSearchInfoId,2)
          this.crud.data = res.content
        } finally{
          this.$store.commit('hjuser/updatedsystemSearchInfoId', '')
        }
      }
      return true;
    },
    showIngredientDialog(info){
      this.ingredientDialog = true
      this.currentShowIngredient = info
    },
    showDialog(row){
      this.isShowAddNumDialog= true
      this.name = row.name
      this.type = row.type
    },
  }
}
</script>

<style scoped></style>
